/**
 *  This program is free software; you can redistribute it and/or modify it under 
 *  the terms of the GNU General Public License as published by the Free Software 
 *  Foundation; either version 3 of the License, or (at your option) any later 
 *  version.
 *  You should have received a copy of the GNU General Public License along with 
 *  this program; if not, see <http://www.gnu.org/licenses/>. 
 *  Use this application at your own risk.
 *
 *  Copyright (c) 2009 by Harald Mueller and Sofia Lemons.
 */

package android.tether;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;

import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context; //import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.tether.data.ClientAdapter;
import android.tether.data.ClientData;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TetherApplication application = null;
	private ProgressDialog progressDialog;

	private RelativeLayout batteryTemperatureLayout = null;

	private TextView batteryTemperature = null;
	private TextView testTxt = null;
	private Button testbtn = null;
	private OnClickListener testlisten = null;

	private static int ID_DIALOG_STARTING = 0;
	private static int ID_DIALOG_STOPPING = 1;

	public static final int MESSAGE_CHECK_LOG = 1;
	public static final int MESSAGE_CANT_START_TETHER = 2;

	public static final String MSG_TAG = "TETHER -> MainActivity";
	public static MainActivity currentInstance = null;

	private static void setCurrent(MainActivity current) {
		MainActivity.currentInstance = current;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(MSG_TAG, "Calling onCreate()");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Init Application
		this.application = (TetherApplication) this.getApplication();
		MainActivity.setCurrent(this);

		// Init Table-Rows
		this.batteryTemperatureLayout = (RelativeLayout) findViewById(R.id.layoutBatteryTemp);
		this.batteryTemperature = (TextView) findViewById(R.id.batteryTempText);

		this.testbtn = (Button) this.findViewById(R.id.button1);
		this.testTxt = (TextView) this.findViewById(R.id.textView1);

		this.testlisten = new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String s = "\n";
				try {
					ArrayList<ClientData> cdata = ClientAdapter.rows;
					for (int i = 0; i < cdata.size(); i++) {
						ClientData cd1 = cdata.get(i);
						s = s + "Name: " + cd1.getClientName() + "\nIP: "
								+ cd1.getIpAddress() + "\nMAC: "
								+ cd1.getMacAddress() + "\n";
					}
					testTxt.setText(s);
					try {
			            for (Enumeration<NetworkInterface> en = NetworkInterface
			                    .getNetworkInterfaces(); en.hasMoreElements();) {
			                NetworkInterface intf = en.nextElement();
			                for (Enumeration<InetAddress> enumIpAddr = intf
			                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
			                    InetAddress inetAddress = enumIpAddr.nextElement();
			                    if (!inetAddress.isLoopbackAddress()) {
			                    	testTxt.append("\nMy IP: "+inetAddress.getHostAddress().toString());
			                        //return inetAddress.getHostAddress().toString();
			                    }
			                }
			            }
			        } catch (SocketException ex) {
			            //Log.e(tag, ex.toString());
			        }

					
				} catch (Exception e) {
					MainActivity.this.application.displayToastMessage(e
							.toString());
				}
			}
		};
		this.testbtn.setOnClickListener(this.testlisten);
	}

	public void onStop() {
		Log.d(MSG_TAG, "Calling onStop()");
		super.onStop();
	}

	public void onDestroy() {
		Log.d(MSG_TAG, "Calling onDestroy()");
		super.onDestroy();
		try {
			unregisterReceiver(this.intentReceiver);
		} catch (Exception ex) {
			;
		}
	}

	public void onResume() {
		Log.d(MSG_TAG, "Calling onResume()");
		// this.showRadioMode();
		super.onResume();

		// Check, if the battery-temperatur should be displayed
		if (this.application.settings.getString("batterytemppref", "celsius")
				.equals("disabled") == false) {
			// create the IntentFilter that will be used to listen
			// to battery status broadcasts
			this.intentFilter = new IntentFilter();
			this.intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
			registerReceiver(this.intentReceiver, this.intentFilter);
			this.batteryTemperatureLayout.setVisibility(View.VISIBLE);
		} else {
			try {
				unregisterReceiver(this.intentReceiver);
			} catch (Exception ex) {
				;
			}
			this.batteryTemperatureLayout.setVisibility(View.INVISIBLE);
		}
	}

	private static final int MENU_SETUP = 0;
	private static final int MENU_LOG = 1;
	private static final int MENU_ABOUT = 2;
	private static final int MENU_ACCESS = 3;
	private static final int MENU_TETHER = 4;
	private static final int MENU_EXIT = 5;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean supRetVal = super.onCreateOptionsMenu(menu);
		SubMenu setup = menu.addSubMenu(0, MENU_SETUP, 0,
				getString(R.string.main_activity_settings));
		setup.setIcon(drawable.ic_menu_preferences);
		if (this.application.accessControlSupported) {
			SubMenu accessctr = menu.addSubMenu(0, MENU_ACCESS, 0,
					getString(R.string.main_activity_accesscontrol));
			accessctr.setIcon(drawable.ic_menu_manage);
		}
		SubMenu log = menu.addSubMenu(0, MENU_LOG, 0,
				getString(R.string.main_activity_showlog));
		log.setIcon(drawable.ic_menu_agenda);

		SubMenu exit = menu.addSubMenu(0, MENU_EXIT, 0,
				getString(R.string.main_activity_exit));
		exit.setIcon(drawable.ic_lock_power_off);

		SubMenu tether = menu.addSubMenu(0, MENU_TETHER, 0,
				getString(R.string.main_activity_tether));
		tether.setIcon(drawable.alert_dark_frame);
		SubMenu about = menu.addSubMenu(0, MENU_ABOUT, 0,
				getString(R.string.main_activity_about));
		about.setIcon(drawable.ic_menu_info_details);
		return supRetVal;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem menuItem) {
		boolean supRetVal = super.onOptionsItemSelected(menuItem);
		Log.d(MSG_TAG, "Menuitem:getId  -  " + menuItem.getItemId());
		try {
			switch (menuItem.getItemId()) {
			case MENU_SETUP:
				startActivityForResult(new Intent(MainActivity.this,
						SetupActivity.class), 0);
				break;
			case MENU_LOG:
				startActivityForResult(new Intent(MainActivity.this,
						LogActivity.class), 0);
				break;
			case MENU_ABOUT:
				this.openAboutDialog();
				break;
			case MENU_ACCESS:
				startActivityForResult(new Intent(MainActivity.this,
						AccessControlActivity.class), 0);
				break;
			case MENU_TETHER:
				startActivityForResult(new Intent(MainActivity.this,
						TetherActivity.class), 0);
				break;
			case MENU_EXIT:
				this.stopApp();
				break;
			}

		} catch (Exception e) {
			MainActivity.this.application.displayToastMessage(e.toString());
		}

		return supRetVal;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == ID_DIALOG_STARTING) {
			progressDialog = new ProgressDialog(this);
			progressDialog.setTitle(getString(R.string.main_activity_start));
			progressDialog
					.setMessage(getString(R.string.main_activity_start_summary));
			progressDialog.setIndeterminate(false);
			progressDialog.setCancelable(true);
			return progressDialog;
		} else if (id == ID_DIALOG_STOPPING) {
			progressDialog = new ProgressDialog(this);
			progressDialog.setTitle(getString(R.string.main_activity_stop));
			progressDialog
					.setMessage(getString(R.string.main_activity_stop_summary));
			progressDialog.setIndeterminate(false);
			progressDialog.setCancelable(true);
			return progressDialog;
		}
		return null;
	}

	/**
	 *Listens for intent broadcasts; Needed for the temperature-display
	 */
	private IntentFilter intentFilter;

	private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
				int temp = (intent.getIntExtra("temperature", 0));
				int celsius = (int) ((temp + 5) / 10);
				int fahrenheit = (int) (((temp / 10) / 0.555) + 32 + 0.5);
				Log.d(MSG_TAG, "Temp ==> " + temp + " -- Celsius ==> "
						+ celsius + " -- Fahrenheit ==> " + fahrenheit);
				if (MainActivity.this.application.settings.getString(
						"batterytemppref", "celsius").equals("celsius")) {
					batteryTemperature
							.setText(""
									+ celsius
									+ getString(R.string.main_activity_temperatureunit_celsius));
				} else {
					batteryTemperature
							.setText(""
									+ fahrenheit
									+ getString(R.string.main_activity_temperatureunit_fahrenheit));
				}
			}
		}
	};

	public Handler viewUpdateHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_CHECK_LOG:
				Log.d(MSG_TAG, "Error detected. Check log.");
				MainActivity.this.application
						.displayToastMessage(getString(R.string.main_activity_start_errors));
				break;
			case MESSAGE_CANT_START_TETHER:
				Log.d(MSG_TAG, "Unable to start tethering!");
				MainActivity.this.application
						.displayToastMessage(getString(R.string.main_activity_start_unable));
				break;
			}
			super.handleMessage(msg);
		}
	};

	// private void openNoNetfilterDialog() {
	// LayoutInflater li = LayoutInflater.from(this);
	// View view = li.inflate(R.layout.nonetfilterview, null);
	// new AlertDialog.Builder(MainActivity.this).setTitle(
	// getString(R.string.main_activity_nonetfilter)).setView(view)
	// .setNegativeButton(getString(R.string.main_activity_exit),
	// new DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog,
	// int whichButton) {
	// Log.d(MSG_TAG, "Close pressed");
	// MainActivity.this.finish();
	// }
	// }).setNeutralButton(
	// getString(R.string.main_activity_ignore),
	// new DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog,
	// int whichButton) {
	// Log.d(MSG_TAG, "Override pressed");
	// MainActivity.this.application
	// .displayToastMessage("Ignoring, note that this application will NOT work correctly.");
	// }
	// }).show();
	// }
	//
	// private void openNoAccessControlDialog() {
	// LayoutInflater li = LayoutInflater.from(this);
	// View view = li.inflate(R.layout.noaccesscontrolview, null);
	// new AlertDialog.Builder(MainActivity.this).setTitle(
	// getString(R.string.main_activity_noaccesscontrol))
	// .setView(view).setNeutralButton(
	// getString(R.string.main_activity_ok),
	// new DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog,
	// int whichButton) {
	// Log.d(MSG_TAG, "OK pressed");
	// MainActivity.this.application
	// .displayToastMessage(getString(R.string.main_activity_accesscontrol_disabled));
	// }
	// }).show();
	// }
	//
	// private void openNotRootDialog() {
	// LayoutInflater li = LayoutInflater.from(this);
	// View view = li.inflate(R.layout.norootview, null);
	// new AlertDialog.Builder(MainActivity.this).setTitle(
	// getString(R.string.main_activity_notroot)).setView(view)
	// .setNegativeButton(getString(R.string.main_activity_exit),
	// new DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog,
	// int whichButton) {
	// Log.d(MSG_TAG, "Exit pressed");
	// MainActivity.this.finish();
	// }
	// }).setNeutralButton(
	// getString(R.string.main_activity_ignore),
	// new DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog,
	// int whichButton) {
	// Log.d(MSG_TAG, "Ignore pressed");
	// MainActivity.this.application.installFiles();
	// MainActivity.this.application
	// .displayToastMessage("Ignoring, note that this application will NOT work correctly.");
	// }
	// }).show();
	// }

	private void openAboutDialog() {
		LayoutInflater li = LayoutInflater.from(this);
		View view = li.inflate(R.layout.aboutview, null);
		TextView versionName = (TextView) view.findViewById(R.id.versionName);
		versionName.setText(this.application.getVersionName());

		new AlertDialog.Builder(MainActivity.this).setTitle(
				getString(R.string.main_activity_about)).setView(view)
				.setNeutralButton("Ok", null).setNegativeButton("Cancel", null)
				.show();
	}

	public void stopApp() {
		String tetherStatus = this.application.coretask
				.getProp("tether.status");
		if (tetherStatus.equals("running")) {
			showDialog(MainActivity.ID_DIALOG_STOPPING);
			new Thread(new Runnable() {
				public void run() {
					MainActivity.this.application.stopTether();
					MainActivity.this
							.dismissDialog(MainActivity.ID_DIALOG_STOPPING);
					MainActivity.this.viewUpdateHandler
							.sendMessage(new Message());
				}
			}).start();
			try {
				Thread.sleep(1400);
			} catch (InterruptedException e) {
				// Taking a small nap
			}
			finish();
		} else {
			finish();
		}

	}
}